package com.stox.ui.javafx.charting.event.listener;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.AbstractModel.Type;
import com.stox.dto.Scrip;
import com.stox.dto.intf.AbstractModelNavigable;
import com.stox.event.AbstractModelSelectionEvent;
import com.stox.ui.javafx.charting.view.ChartingViewDisplayHelper;

@Component
@Lazy(false)
public class AbstractModelSelectionEventListener implements SmartApplicationListener {
	
	@Autowired
	private ChartingViewDisplayHelper chartingViewDisplayHelper;
	
	@Override
	@SuppressWarnings("unchecked")
	public void onApplicationEvent(ApplicationEvent event) {
		AbstractModelNavigable<? extends Collection<AbstractModel>> abstractModelNavigable = (AbstractModelNavigable<? extends Collection<AbstractModel>>)event.getSource();
		Collection<AbstractModel> models = abstractModelNavigable.get();
		models = getModelsOfType(models, Scrip.ScripType.ANY);
		if(!models.isEmpty()){
			chartingViewDisplayHelper.display(abstractModelNavigable);
		}
	}
	
	private Collection<AbstractModel> getModelsOfType(Collection<AbstractModel> models, Type type){
		Collection<AbstractModel> result = new ArrayList<AbstractModel>();
		for(AbstractModel abstractModel : models){
			if(abstractModel.getType().isSubTypeOf(type)){
				result.add(abstractModel);
			}
		}
		return result;
	}
	
	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public boolean supportsEventType(Class<? extends ApplicationEvent> clazz) {
		return AbstractModelSelectionEvent.class.isAssignableFrom(clazz);
	}

	@Override
	public boolean supportsSourceType(Class<?> clazz) {
		return AbstractModelNavigable.class.isAssignableFrom(clazz);
	}
	
}
